﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.IO;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Excel = Microsoft.Office.Interop.Excel;

namespace KnowledgeAssistant
{
    public partial class PrintPreviewForm : Form
    {

        private int archive_test_id;
        private string Html;
        private DataTable testinfo;
        private DataTable questionsinfo;
        private DataTable answersTable;
        private int group_id;
        private DataTable groupData;

        public PrintPreviewForm(int archive_test_id)
        {
            InitializeComponent();
            List<string> parameters = new List<string>() { };
            parameters.Add("0");            
            parameters.Add("0");
            parameters.Add(archive_test_id.ToString());
            this.archive_test_id = archive_test_id;
            this.testinfo = DatabaseConnect.execSP("GetTestResults",parameters).Tables[0];
            DataSet tables = TestUtil.GetTestResultsInfo(this.archive_test_id);
            this.questionsinfo = tables.Tables[0];
            this.answersTable = tables.Tables[1];
            GenerateHtmlPreview();
            this.webBrowser1.DocumentText = this.Html;
        }

        public PrintPreviewForm(int archive_test_id, int group_id)
        {
            InitializeComponent();
            List<string> parameters = new List<string>() { };
            parameters.Add("0");
            parameters.Add(group_id.ToString());
            parameters.Add("0");
            this.group_id = group_id;
            this.groupData = DatabaseConnect.execSP("GetTestResults", parameters).Tables[0];
            GenerateHtmlpreviewForGroup();
            this.webBrowser1.DocumentText = this.Html;
        }

        public PrintPreviewForm(Group g)
        {
            InitializeComponent();            
            GenerateHtmlpreviewForStudents(g);
            this.webBrowser1.DocumentText = this.Html;
        }

        public PrintPreviewForm()
        {
            InitializeComponent();
            GenerateHtmlpreviewForTeachers();
            this.webBrowser1.DocumentText = this.Html;
        }

        private void GenerateHtmlpreviewForTeachers()
        {
            DataTable table = DatabaseConnect.execSP("GetTeachersWithUserData", new List<string>() { 0.ToString() }).Tables[0];
            string HtmlHeader = "<html><title>Список преподавателей: логины и пароли</title><body><basefont size=\"6\">";
            HtmlHeader += "<p></p>";
            string StatisticsTable = "";
            DataRow[] rows = table.Select("", "lname, mname, fname, user_name, user_pass");            
            StatisticsTable += "<p><b>Преподаватели</p>";            
            StatisticsTable += "<p><table style=\"font-size:25px\" cellspacing=\"0\" border=\"3\">";
            StatisticsTable +=
                            "<tr>"
                                + "<td width=\"320\"><b>ФИО</td>"
                                + "<td width=\"150\"><b>Логин</td>"
                                + "<td width=\"170\"><b>Пароль</td>"
                          + "</tr>";

            foreach (DataRow row in rows)
            {                                
                StatisticsTable +=
                   "<tr>"
                       + "<td width=\"320\">" + row["lname"] + " " + row["fname"] + " " + row["mname"] + "</td>"
                       + "<td width=\"150\">" + row["user_name"] + "</td>"
                       + "<td width=\"170\">" + row["user_pass"] + "</td>"
                 + "</tr>";
            }

            StatisticsTable += "</table></p>";
            string HtmlFooter = "</body></html>";
            Html = HtmlHeader + StatisticsTable + HtmlFooter;
        }

        private void GenerateHtmlpreviewForStudents(Group g)
        {
            DataTable table = DatabaseConnect.execSP("GetStudentsByGroupWithUserData", new List<string>() { g.GroupID.ToString() }).Tables[0];
            string HtmlHeader = "<html><title>Группа " + g.GroupNumber + ":  " + g.GroupName + " - логины и пароли" +"</title><body><basefont size=\"6\">";
            HtmlHeader += "<p></p>";
            string StatisticsTable = "";
            DataRow[] rows = table.Select("", "student_id, lname, mname, fname, record_book_number, group_number, user_name, user_pass");            
            StatisticsTable += "<p><b>Группа: " + g.GroupNumber + "</p>";            
            StatisticsTable += "<p><table style=\"font-size:25px\" cellspacing=\"0\" border=\"3\">";
            StatisticsTable +=
                            "<tr>"
                                + "<td width=\"320\"><b>ФИО</td>"
                          //    + "<td width=\"100\">Зач. книжка</td>"
                                + "<td width=\"150\"><b>Логин</td>"
                                + "<td width=\"170\"><b>Пароль</td>"
                          + "</tr>";

            foreach (DataRow row in rows)
            {                                
                StatisticsTable +=
                   "<tr>"
                       + "<td width=\"320\">" + row["lname"] + " " + row["fname"] + " " + row["mname"] + "</td>"
                //     + "<td width=\"100\">" + row["record_book_number"] + "</td>"
                       + "<td width=\"150\">" + row["user_name"] + "</td>"
                       + "<td width=\"170\">" + row["user_pass"] + "</td>"
                 + "</tr>";
            }

            StatisticsTable += "</table></p>";
            string HtmlFooter = "</body></html>";
            Html = HtmlHeader + StatisticsTable + HtmlFooter;
        }

        private void GenerateHtmlpreviewForGroup()
        {
            Group g = GroupUtil.GetGroup(this.group_id);

            string HtmlHeader = "<html><title>" + g.GroupNumber + ": " + g.GroupName + " - Результаты тестирования " +"</title><body><basefont size=\"5\">";

            HtmlHeader += "<p></p>";

            string StatisticsTable = "";

            DataRow[] rows = this.groupData.Select("", "subject_name asc, theme_name asc, fio asc");

            string current_sbj = rows[0]["subject_name"].ToString();
            string current_theme = rows[0]["theme_name"].ToString();

            StatisticsTable += "<p>Предмет: " + current_sbj + "</p>";
            StatisticsTable += "<p>Тема: " + current_theme + "</p>";
            StatisticsTable += "<p>Группа: " + g.GroupNumber + "</p>";    

            StatisticsTable += "<p><table style=\"font-size:18px\" cellspacing=\"0\" border=\"1\">";

            StatisticsTable +=
                            "<tr>"
                                + "<td width=\"100\"><b>ФИО</td>"
                         //     + "<td width=\"100\">Предмет</td>"
                         //     + "<td width=\"100\">Тема</td>"
                                + "<td width=\"100\"><b>Верно</td>"
                                + "<td width=\"100\"><b>Неверно</td>"
                                + "<td width=\"100\"><b>Набрано</td>"
                                + "<td width=\"100\"><b>Максимум</td>"
                                + "<td width=\"100\"><b>%</td>"
                                + "<td width=\"100\"><b>Оценка</td>"
                                + "<td width=\"100\"><b>Затрачено</td>"
                                + "<td width=\"100\"><b>Дата</td>"
                          + "</tr>";

            foreach (DataRow row in rows)
            {
                if (current_sbj != row["subject_name"].ToString() || current_theme != row["theme_name"].ToString())
                {

                    StatisticsTable += "</table></p>";

                    StatisticsTable += "<p><b>Предмет: " + row["subject_name"].ToString() + "</b></p>";
                    StatisticsTable += "<p><b>Тема: " + row["theme_name"].ToString() + "</b></p>";

                    StatisticsTable += "<p><table cellspacing=\"0\" border=\"1\">";

                    StatisticsTable +=
                            "<tr>"
                                + "<td width=\"100\">ФИО</td>"
                          //    + "<td width=\"100\">Предмет</td>"
                          //    + "<td width=\"100\">Тема</td>"
                                + "<td width=\"100\">Верно</td>"
                                + "<td width=\"100\">Неверно</td>"
                                + "<td width=\"100\">Набрано</td>"
                                + "<td width=\"100\">Максимум</td>"
                                + "<td width=\"100\">%</td>"
                                + "<td width=\"100\">Оценка</td>"
                                + "<td width=\"100\">Затрачено</td>"
                                + "<td width=\"100\">Дата</td>"
                          + "</tr>";
                }

                StatisticsTable +=
                   "<tr>"
                       + "<td width=\"100\">" + row["fio"] + "</td>"
                    // + "<td width=\"100\">" + row["subject_name"] + "</td>"
                    // + "<td width=\"100\">" + row["theme_name"] + "</td>"
                       + "<td width=\"100\">" + row["countoftrue"] + "</td>"
                       + "<td width=\"100\">" + row["countoffalse"] + "</td>"
                       + "<td width=\"100\">" + row["passed_points"] + "</td>"
                       + "<td width=\"100\">" + row["max_points"] + "</td>"
                       + "<td width=\"100\">" + row["percents"] + "</td>"
                       + "<td width=\"100\">" + row["mark"] + "</td>"
                       + "<td width=\"100\">" + row["duration_time"] + "</td>"
                       + "<td width=\"100\">" + row["date_begin"] + "</td>"
                 + "</tr>";

                current_sbj = row["subject_name"].ToString();
                current_theme = row["theme_name"].ToString();
            }

            StatisticsTable += "</table></p>";

            string HtmlFooter = "</body></html>";

            Html = HtmlHeader + StatisticsTable + HtmlFooter;
        }

        private void GenerateHtmlPreview()
        {
            string HtmlHeader = "<html><title>" + this.testinfo.Rows[0]["fio"].ToString()
                + ", " + this.testinfo.Rows[0]["subject_name"].ToString()
                + ", " + this.testinfo.Rows[0]["theme_name"].ToString()
                + ", " + this.testinfo.Rows[0]["date_begin"].ToString()
                + "</title><body><basefont size=\"4\">";
            string HtmlFooter = "</body></html>";

            string TableForFirstStage = "<table style=\"font-size:18px\" cellspacing=\"0\" border=\"2\">"
                + "<tr><td width=\"130\"><b>№</td>"
                + "<td width=\"100\"><b>Уровень</td>"
                + "<td width=\"60\"><b>Балл</td>"
                + "<td width=\"100\"><b>Верно/Нет</td>"
                + "<td width=\"100\"><b>Начислено</td></tr>";

            string TableForSecondStage = "<table style=\"font-size:18px\" cellspacing=\"0\" border=\"2\">"
                + "<tr><td width=\"130\"><b>№</td>"
                + "<td width=\"100\"><b>Уровень</td>"
                + "<td width=\"100\"><b>Балл</td>"
                + "<td width=\"100\"><b>Верно/Нет</td>"
                + "<td width=\"100\"><b>Начислено</td></tr>";

            string TableForFirstAnswersDetails = "<table style=\"font-size:18px\" cellspacing=\"0\" border=\"2\">";
            TableForFirstAnswersDetails = "<p>Вопросы 1-го этапа: подробно</p>" + TableForFirstAnswersDetails;
            string TableForSecondAnswersDetails = "<table style=\"font-size:18px\" cellspacing=\"0\" border=\"2\">";
            TableForSecondAnswersDetails = "<p><b>Вопросы 2-го этапа: подробно</b></p>" + TableForSecondAnswersDetails;

            string HtmlBody = "";

            HtmlBody += "<table style=\"font-size:20px\">";

            HtmlBody += "<tr><td>Тестируемый:</td><td>" + this.testinfo.Rows[0]["fio"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Группа:</td><td>" + this.testinfo.Rows[0]["group_number"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Предмет:</td><td>" + this.testinfo.Rows[0]["subject_name"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Тема:</td><td>" + this.testinfo.Rows[0]["theme_name"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Набранный процент:</td><td>" + this.testinfo.Rows[0]["percents"].ToString() + " % </td></tr>";
            //HtmlBody += this.testinfo.Rows[0]["countoftrue"] + "</td></tr>";
            //HtmlBody += this.testinfo.Rows[0]["countoffalse"] + "</td></tr>";
            HtmlBody += "<tr><td>Набранный балл:</td><td>" + this.testinfo.Rows[0]["passed_points"].ToString()
                + " из " + this.testinfo.Rows[0]["max_points"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Оценка:</td><td>" + this.testinfo.Rows[0]["mark"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Время прохождения:</td><td>" + this.testinfo.Rows[0]["duration_time"].ToString() + "</td></tr>";
            HtmlBody += "<tr><td>Дата прохождения:</td><td>" + this.testinfo.Rows[0]["date_begin"].ToString() + "</td></tr>";

            HtmlBody += "</table><p>";

            int i = 1;
            int j = 1;
            string arc_question_id;

            foreach (DataRow row in this.questionsinfo.Rows)
            {
                arc_question_id = row["archive_question_id"].ToString();
                if (row["question_type"].ToString() == "1")
                {
                    TableForFirstStage +=
                        "<tr><td width=\"100\">Задание " + (i++).ToString() + " </td>"
                        + "<td width=\"100\">" + row["levelname"].ToString() + "</td>"
                        + "<td width=\"100\">" + row["level_value"].ToString() + "</td>"
                        + "<td width=\"100\">" + ((row["true"].ToString() == "0") ? "Да" : "Нет") + "</td>"
                        + "<td>" + ((row["true"].ToString() == "0") ? row["level_value"].ToString() : "0") + "</td></tr>";

                    TableForFirstAnswersDetails += "<tr><td colspan=\"3\"><b>Задание " + (i - 1) + "</b></td></tr>";
                    TableForFirstAnswersDetails += "<tr><td colspan=\"3\">&#8195 " + row["description"];

                    byte[] img = null;
                    object temp = row["question_image"];
                    if (temp is byte[])
                    {
                        img = (byte[])temp;
                    //    img = ResizeImg(img);
                        TableForFirstAnswersDetails += String.Format("<p><img  src=\"data:image/jpg;base64,{0}\" style=\"margin: 0px 0px 10px 23px\"  weight=\"250\" border=\"1\"></p>", Convert.ToBase64String(img)); //style=\"float: left; margin: 0px 0px 0px 0px\"
                    }

                    TableForFirstAnswersDetails += "</td></tr>";

                    //image!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                    foreach (DataRow rowa in answersTable.Select("archive_question_id = " + arc_question_id))
                    {
                        bool checkedsymbol = (((bool)rowa["checked"]) ? true : false);
                        string trueString = "";
                        if ((bool)rowa["true"])
                        {
                            if (checkedsymbol)
                            {
                                trueString = "Правильно";
                            }
                            //else
                            //{
                            //    trueString = "Неверно";
                            //}
                        }
                        else if (!(bool)rowa["true"])
                        {
                            if (checkedsymbol)
                            {
                                trueString = "Неверно";
                            }
                        }

                        string backcolor = "";
                        switch (trueString)
                        {
                            case "": backcolor = "#ffffff"; break;
                            case "Правильно": backcolor = "#99ff99"; break;
                            case "Неверно": backcolor = "#ff7f50"; break;
                        }


                        TableForFirstAnswersDetails += "<tr bgcolor=\"" + backcolor + "\">"
                              + "<td width=\"870\">&#8195&#8195&#9899  " + rowa["description"].ToString() + "</td>"
                              + "<td width=\"30\">&nbsp;" + ((checkedsymbol) ? "&#8730" : "&#9675") + "</td>"
                            + "<td width=\"120\">&nbsp;" + trueString + "</td>"
                            + "</tr>";
                    }
                }
                else
                {
                    TableForSecondStage +=
                        "<tr><td>Задание " + (j++).ToString() + "</td>"
                        + "<td>" + row["levelname"].ToString() + "</td>"
                        + "<td>" + row["level_value"].ToString() + "</td>"
                        + "<td>" + ((row["true"].ToString() == "0") ? "Да" : "Нет") + "</td>"
                        + "<td>" + ((row["true"].ToString() == "0") ? row["level_value"].ToString() : "0") + "</td></tr>";

                    TableForSecondAnswersDetails += "<tr><td colspan=\"3\"><b>Задание " + (j - 1) + "</b></td></tr>";
                    TableForSecondAnswersDetails += "<tr><td colspan=\"3\">&#8195 " + row["description"];

                    byte[] img = null;
                    object temp = row["question_image"];
                    if (temp is byte[])
                    {
                        img = (byte[])temp;
                     //   img = ResizeImg(img);
                        TableForSecondAnswersDetails += String.Format("<p><img  src=\"data:image/jpg;base64,{0}\" style=\"margin: 0px 0px 10px 23px\" weight=\"250\" border=\"1\"></p>", Convert.ToBase64String(img)); //style=\"float: left; margin: 0px 0px 0px 0px\"
                    }

                    TableForSecondAnswersDetails += "</td></tr>";

                    foreach (DataRow rowa in answersTable.Select("archive_question_id = " + arc_question_id))
                    {
                        bool checkedsymbol = (((bool)rowa["checked"]) ? true : false);
                        string trueString = "";
                        string backcolor = "";
                        if ((bool)rowa["true"])
                        {
                            if (checkedsymbol)
                            {
                                trueString = "Правильно";
                                backcolor = "#99ff99";
                            }
                            else
                            {
                                trueString = "Ошибка - не было выбрано";
                                backcolor = "ffff00";
                            }
                        }
                        else if (!(bool)rowa["true"])
                        {
                            if (checkedsymbol)
                            {
                                trueString = "Неверно";
                                backcolor = "#ff7f50";
                            }
                        }
                        else { backcolor = "#ffffff"; }

                        //switch (trueString)
                        //{
                        //    case "": backcolor = "#ffffff"; break;
                        //    case "Верно": backcolor = "#99ff99"; break;
                        //    case "Ошибка": backcolor = "#ff7f50"; break;
                        //}

                        TableForSecondAnswersDetails += "<tr bgcolor=\"" + backcolor + "\">"
                            + "<td width=\"900\">&#8195&#8195&#9899  " + rowa["description"].ToString() + "</td>"
                            + "<td width=\"30\">&nbsp;" + ((checkedsymbol) ? "&#8730" : "&#9675") + "</td>"
                            + "<td width=\"120\">&nbsp;" + trueString + "</td>"
                            + "</tr>";
                    }
                }
            }

            TableForFirstAnswersDetails += "</table>";
            TableForFirstAnswersDetails = "<p>" + TableForFirstAnswersDetails + "</p>";
            TableForSecondAnswersDetails += "</table>";
            TableForSecondAnswersDetails = "<p>" + TableForSecondAnswersDetails + "</p>";

            TableForFirstStage += "</table>";
            TableForFirstStage = "<p>Первый этап</p>" + TableForFirstStage;
            TableForFirstStage = "<p>" + TableForFirstStage + "</p>";
            TableForSecondStage += "</table>";
            TableForSecondStage = "<p>Второй этап</p>" + TableForSecondStage;
            TableForSecondStage = "<p>" + TableForSecondStage + "</p>";

            HtmlBody = "<p>Общая информация</p>" + HtmlBody;
            HtmlBody = "<p><b>Результаты тестирования<b></p>" + HtmlBody;
            HtmlBody = "<p>" + HtmlBody + "</p>";

            HtmlBody += TableForFirstStage + TableForSecondStage + TableForFirstAnswersDetails + TableForSecondAnswersDetails;

            this.Html = HtmlHeader + HtmlBody + HtmlFooter;
        }

        private void PrintPreviewForm_Load(object sender, EventArgs e)
        {

        }

        private void InitFields()
        {

        }

        StreamReader streamToPrint = null;
        private void button3_Click(object sender, EventArgs e)
        {
            this.webBrowser1.ShowPrintPreviewDialog();
        }

        private object _missingObj = System.Reflection.Missing.Value;

        private void button1_Click(object sender, EventArgs e)
        {

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "xls-files|*.xls";
            sfd.ShowDialog();

            if (sfd.FileName != "" && sfd.FileName != null)
            {
                Excel.Worksheet oSheet;
                Excel.Application xlApp = new Excel.Application();
                xlApp.Workbooks.Add(Type.Missing);
                xlApp.Interactive = false;
                xlApp.EnableEvents = false;
                oSheet = (Excel.Worksheet)xlApp.ActiveSheet;
                webBrowser1.Document.ExecCommand("SelectAll", false, null);
                webBrowser1.Document.ExecCommand("Copy", false, null);
                oSheet.Paste();
                oSheet.SaveAs(sfd.FileName, Excel.XlFileFormat.xlXMLSpreadsheet,
                    false, false,
                false, false, Excel.XlSaveAsAccessMode.xlNoChange, false, false, false);
                oSheet = null;
                xlApp.Interactive = true;
                xlApp.ScreenUpdating = true;
                xlApp.UserControl = true;

                int id;
                GetWindowThreadProcessId(xlApp.Hwnd, out id);
                Process.GetProcessById(id).Kill();
            }
        }

        [DllImport("user32.dll")]
        static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);

        public byte[] ResizeImg(byte[] b)
        {
            byte[] resbytes = null;

            MemoryStream ms = new MemoryStream(b);
            Bitmap map = new Bitmap(ms);

            int width = map.Width;
            int height = map.Height;

            int nWidth = 500;
            float percent = (nWidth * 100 / (float)width);
            int nHeight = (int)(percent * height) / 100;

            Image result = new Bitmap(nWidth, nHeight);
            using (Graphics g = Graphics.FromImage((Image)result))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(map, 0, 0, nWidth, nHeight);
                g.Dispose();
            }

            MemoryStream msr = new MemoryStream();
            result.Save(msr, System.Drawing.Imaging.ImageFormat.Jpeg);
            resbytes = msr.ToArray();

            msr.Close();
            ms.Close();

            return resbytes;
        }


    }
}
